package com.software.admincenter.service;

import com.software.admincenter.entity.AdminInfo;
import com.software.admincenter.repository.AdminInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: huanhuan
 * @Date: 2023-06-13 08:42
 **/
@Service
@Transactional
public class AdminInfoService {
    @Autowired
    private AdminInfoRepository adminInfoRepository;

    public Page<AdminInfo> findAll(Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        return adminInfoRepository.findAll(pageable);
    }

    public AdminInfo addAdminInfo(AdminInfo adminInfo) {
        adminInfo.setIsUse("Y");
        return adminInfoRepository.save(adminInfo);
    }

    public AdminInfo findById(Integer id) {
        Optional<AdminInfo> optional = adminInfoRepository.findById(id);
        return optional.get();
    }

    public void deleteAdminInfoByAdminId(String adminId) {
        AdminInfo adminInfo = findById(Integer.valueOf(adminId));
        adminInfoRepository.delete(adminInfo);
    }

    public void updateAdminInfo(AdminInfo adminInfo) {
        adminInfoRepository.save(adminInfo);
    }

    public Page<AdminInfo> findAdminInfosByAdminNameLike(String adminName, Integer pageNo, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNo, pageSize);
        Specification<AdminInfo> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (adminName != null && !adminName.isEmpty()) {
                predicates.add(cb.like(root.get("adminName"), "%" + adminName + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return adminInfoRepository.findAll(spec, pageable);
    }

    public List<AdminInfo> verifyLogin(String adminName, String password) {
        List<AdminInfo> adminInfos = adminInfoRepository.findAdminInfosByAdminNameAndPasswordAndIsUse(adminName, password, "Y");
        return  adminInfos;
    }
}
